﻿using ResxHelper.Object;
using System.Globalization;
using System.IO;
using System.Linq;

namespace ResxHelper.Logic.Readers
{
    public class IOSResourceFileReader : IResourceFileReader
    {
        public string Path { get; private set; }

        public IOSResourceFileReader(string path)
        {
            Path = path;
        }

        public ResourceFile Read()
        {
            var resourceFile = new ResourceFile {  CultureInfo = GetCulture(), FilePath = Path };
            using (var sr = new StreamReader(Path))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    if(!IsEntry(line)) continue;

                    string key;
                    var entry = GetEntry(out key, line);
                    resourceFile.Entries.Add(key, entry);
                }
            }

            return resourceFile;
        }

        private CultureInfo GetCulture()
        {
            var directory = System.IO.Path.GetDirectoryName(Path);
            var directoryName = directory.Split('\\').LastOrDefault();
            var cultureStr = directoryName.Split('.').FirstOrDefault();
            return new CultureInfo(cultureStr);
        }

        private ResourceFileEntry GetEntry(out string key, string entry)
        {
            var entrySplit = entry.Split('=');
            key = CleanString(entrySplit[0]);
            var value = CleanString(entrySplit[1]);

            var resourceEntry = new ResourceFileEntry {Key = key, Value = value};
            return resourceEntry;
        }

        private static string CleanString(string val)
        {
            var badCharacters = new[] {"\\", ";", "\""};

            var cleanString = val;
            foreach (var character in badCharacters)
            {
                cleanString = cleanString.Replace(character, string.Empty);
            }

            return cleanString;
        }

        private static bool IsEntry(string line)
        {
            return
                line.StartsWith("\"") && line.EndsWith(";");
        }
    }
}
